import platform
import subprocess
import winreg
import os
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import argparse

def get_chrome_version():
    system = platform.system()
    try:
        if system == "Windows":
            try:
                key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Google\Chrome\BLBeacon")
                version, _ = winreg.QueryValueEx(key, "version")
                winreg.CloseKey(key)
                return version
            except (FileNotFoundError, OSError):
                try:
                    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Wow6432Node\Google\Chrome\BLBeacon")
                    version, _ = winreg.QueryValueEx(key, "version")
                    winreg.CloseKey(key)
                    return version
                except (FileNotFoundError, OSError):
                    return None
        elif system == "Darwin":
            command = r'/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version'
            result = subprocess.run(command, shell=True, capture_output=True, text=True)
            if result.returncode == 0:
                return result.stdout.strip().replace('Google Chrome ', '')
            return None
        elif system == "Linux":
            commands = [
                "google-chrome --version",
                "chromium-browser --version"
            ]
            for command in commands:
                result = subprocess.run(command, shell=True, capture_output=True, text=True)
                if result.returncode == 0:
                    return result.stdout.strip().split(' ')[-1]
            return None
        else:
            return None
    except Exception:
        return None


def prompt_driver_download():
    chrome_version = get_chrome_version()
    if chrome_version:
        print(f"当前谷歌浏览器版本: {chrome_version}")
        store_folder = "chromedriver-store"
        current_dir = os.getcwd()
        full_path = os.path.join(current_dir, store_folder)

        if not os.path.exists(full_path):
            os.makedirs(full_path)
            print(f"已创建 {full_path} 文件夹。")

        print(f"请访问 https://googlechromelabs.github.io/chrome-for-testing/ 下载与您的谷歌浏览器版本 {chrome_version} 匹配的 ChromeDriver。")
        print(f"下载解压完成后，请将 ChromeDriver.exe 放在 {full_path} 文件夹下。")
    else:
        print("未能获取到谷歌浏览器版本。")


def create_chrome_driver():
    store_folder = "chromedriver-store"
    current_dir = os.getcwd()
    full_path = os.path.join(current_dir, store_folder)
    driver_path = None
    for root, dirs, files in os.walk(full_path):
        for file in files:
            if 'chromedriver' in file.lower():
                driver_path = os.path.join(root, file)
                break
        if driver_path:
            break

    if driver_path:
        try:
            options = webdriver.ChromeOptions()
            # 在 ChromeOptions 对象中加入一个实验性的选项 detach 并设置其值为 True，其作用是实现在程序运行完毕后不要关闭浏览器
            options.add_experimental_option("detach", True)
            options.add_argument("--start-maximized")
            options.add_argument("--disable-blink-features=AutomationControlled")
            # 启动开发者模式(关闭 chrome 控制)
            options.add_experimental_option("excludeSwitches", ["enable-automation"])
            options.add_experimental_option("useAutomationExtension", 'False')
            # 设置用户文件夹为动态 current_dir + 'ChromeUserData'
            user_data_dir = os.path.join(current_dir, 'ChromeUserData')
            options.add_argument(f'--user-data-dir={user_data_dir}')

            service = Service(driver_path)
            driver = webdriver.Chrome(service=service, options=options)
            driver.implicitly_wait(5)
            return driver
        except Exception as e:
            print(f"创建 ChromeDriver 实例时出错: {e}")
    else:
        print("未在 chromedriver-store 文件夹中找到 ChromeDriver。")
    return None


import time
from selenium import webdriver
from selenium.common.exceptions import TimeoutException


class Feishu:
    def __init__(self, driver: webdriver.Chrome):
        self.driver = driver

    def login(self):
        """登录飞书"""
        login_url = 'https://accounts.feishu.cn/'
        self.driver.get(login_url)
        try:
            time.sleep(1)
        except TimeoutException:
            print("Timeout waiting for login element")
        return

    def fill_questionnaire(self,url,contents):
        # self.cookie_login()
        self.driver.get(url)
        flag = False
        xpath = self.driver.find_elements("xpath", '//textarea[@class = "uni-textarea-textarea"]')
        for i,ele in enumerate(xpath[:-1]):
            ele.send_keys(contents[i])  # 将 i.send_keys(i) 修改为 i.send_keys("填写的内容")
        # try :
        #     question= self.driver.find_elements("xpath", '//uni-view[@class = "dynamic-text-inline"]')[-1:]
        #     cacl_question = question[-1].text
        #     # 测试 
        #     # cacl_question = '5-5'
        #     result = eval(cacl_question)
        #     result = round(result, 2)
        #     xpath[-1].send_keys(result)
        #     flag = True
        # except Exception:
        #     print('错误发生，可能为非计算题或者非文本内容')
        # 点击提交
        # if flag :
        #     self.driver.find_element("xpath", '//div[@class="base-form-container_form_submit_btn_wrapper"]//*[@type="button"]').click()
        
        
        
if __name__ == "__main__":
    driver = create_chrome_driver()
    if driver:
        feishu = Feishu(driver)
        # 专利名 姓名 教工号 是否是学校账号 （简单计算）
        start=time.time()  #计时开始
        parser = argparse.ArgumentParser(description='填写飞书问卷所需信息')
        parser.add_argument('--patent_name', type=str, help='专利名')
        parser.add_argument('--teacher_name', type=str, help='姓名')
        parser.add_argument('--Teacher_ID', type=str, help='教工号')
        parser.add_argument('--is_shcool_count', type=str, help='是否是学校账号 (是/否)')
        parser.add_argument('--url', type=str, help='问卷链接')
        args = parser.parse_args()
        
        patent_name = args.patent_name
        teacher_name = args.teacher_name
        Teacher_ID = args.Teacher_ID
        is_shcool_count = args.is_shcool_count
        contents = [patent_name,teacher_name,Teacher_ID,is_shcool_count]
        url = args.url
        # 问卷url
        # url = 'https://wenjuan.feishu.cn/m/cfm?t=sqRtAINQBXWi-a1qp'
        # url = 'https://wenjuan.feishu.cn/m?t=sZQ9fxeUh0Zi-ubt9'
        # url = 'https://swpu.feishu.cn/share/base/form/shrcnvX6pah3tAVd6mLJ1FKs8pg'
        feishu.fill_questionnaire(url,contents)
        end = time.time()  		#计时结束
        print('运行时间：{:.1f}秒'.format(end-start))  	#程序运行时间
    else:
        prompt_driver_download()
    